package com.mzm.tests;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.junit.Assert;
import org.junit.Before;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.Resource;
import org.springframework.test.context.junit4.AbstractTransactionalJUnit4SpringContextTests;

import dnl.jexem.cmd.CommandExecution;
import dnl.jexem.cmd.CommandExecutionFactory;
import dnl.toolbox.lang.ShellEnvironment;

/**
 * 
 * @author Daniel Orr
 *
 */
public abstract class BaseDbBackupTest extends AbstractTransactionalJUnit4SpringContextTests {

	private static final Logger logger = LoggerFactory.getLogger(BaseDbBackupTest.class);

	private static boolean dbRestored;

	public abstract Resource getDbBackupFile();

	@Before
	public void dbRestore() throws Exception {
		if (dbRestored) {
			return;
		}
		Resource dbBackupResource = getDbBackupFile();
		String dbDirStr = "${VALIRE_DIR}/db/scripts/mysql";
		dbDirStr = ShellEnvironment.replaceShellVariables(dbDirStr);
		File dbDir = new File(dbDirStr);

		// copy backup to db dir
		InputStream is = dbBackupResource.getInputStream();
		FileOutputStream out = new FileOutputStream(new File(dbDir, dbBackupResource.getFilename()));
		IOUtils.copy(is, out);
		IOUtils.closeQuietly(is);
		IOUtils.closeQuietly(out);

		String backupLabel = dbBackupResource.getFilename();
		backupLabel = StringUtils.replace(backupLabel, ".db-backup.tar", "");

		// restore db
		CommandExecution commandExecution = CommandExecutionFactory.createLocalCommandExecution("./db_restore.sh",
				backupLabel);
		commandExecution.setWorkDir(dbDirStr);
		commandExecution.executeCommand(true);
		if (commandExecution.getExitStatus() != 0) {
			Assert.fail("Error executing db restore.");
			logger.error(commandExecution.getAllOutputs());
		} else {
			logger.info(commandExecution.getOutput());
		}
		String toolsDirStr = "${VALIRE_DIR}/Tools";
		toolsDirStr = ShellEnvironment.replaceShellVariables(toolsDirStr);

		CommandExecution dbUpgrade = CommandExecutionFactory.createLocalCommandExecution("./db-upgrade-tool");
		dbUpgrade.setWorkDir(toolsDirStr);
		dbUpgrade.executeCommand(true);
		if (dbUpgrade.getExitStatus() != 0) {
			logger.error(dbUpgrade.getAllOutputs());
			Assert.fail("Error executing db upgrade.");
		} else {
			logger.info(dbUpgrade.getOutput());
		}
		dbRestored = true;
	}
}
